import { Sequelize, DataTypes, Model } from 'sequelize';

// 创建 Sequelize 实例
// const sequelize = new Sequelize({
//   dialect: 'sqlite',
//   storage: process.cwd() + '/chat.db',
//   logging: false
// });

const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: process.cwd() + '/chat.db',
  logging: console.log,
  define: {
      timestamps: true, // 默认为每个模型添加 createdAt 和 updatedAt 字段
      underscored: true, // 使用下划线命名方式
  }
});



// 定义 Message 模型
class Message extends Model {
  declare id: number;
  declare sender: string;
  declare content: string;
  declare timestamp: string;
  declare avatar: string;
  declare createdAt: Date;
  declare updatedAt: Date;
}

Message.init({
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  sender: {
    type: DataTypes.STRING,
    allowNull: false
  },
  content: {
    type: DataTypes.STRING,
    allowNull: false
  },
  timestamp: {
    type: DataTypes.STRING,
    allowNull: false
  },
  avatar: {
    type: DataTypes.STRING,
    allowNull: false
  },
  createdAt: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  },
  updatedAt: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  }
}, {
  sequelize,
  modelName: 'Message'
});

// 定义 Todo 模型
class Todo extends Model {
  declare id: number;
  declare text: string;
  declare completed: boolean;
  declare createdAt: Date;
  declare updatedAt: Date;
}

Todo.init({
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  text: {
    type: DataTypes.STRING,
    allowNull: false
  },
  completed: {
    type: DataTypes.BOOLEAN,
    defaultValue: false
  },
  createdAt: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  },
  updatedAt: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  }
}, {
  sequelize,
  modelName: 'Todo'
});

// 测试数据库连接并同步模型
async function initDatabase() {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');
    await sequelize.sync();
    console.log('数据库同步完成');
  } catch (error) {
    console.error('数据库连接失败:', error);
    throw error;
  }
}

// 初始化数据库
initDatabase().catch(error => {
  console.error('数据库初始化失败:', error);
  process.exit(1);
});

export { sequelize, Message, Todo };